<script setup lang="ts">
import NewsComment from "@/components/NewsComment.vue";
import {onMounted, ref} from 'vue'
import {ElMessage, UploadFile, type UploadInstance} from 'element-plus'
import {exitNickName, exitPassword, exitSignatures, uploadAvatar} from "@/request/api/Login";
import {BASE_GOODSIMG_URL} from "@/constant/module/file";
import {getUserPost} from "@/request/api/Posts";
import store from "@/store";
import type {passwordForm} from "@/request/types/user";
import router from "@/router";


let nickName = ref('')
let avatarImg = ref('')

//修改头像
let avatar = ref('')
const handleExceed = (file: UploadFile) => {
  let fd = new FormData()
  fd.append('myFile', file.raw!)
  uploadAvatar(fd).then((res: any) => {
    console.log('图片上传到' + res)
    avatar.value =BASE_GOODSIMG_URL + res
    console.log(avatar.value)
  })
}
const upload = ref<UploadInstance>()
const submitUpload = () => {
  upload.value!.submit()
}

//获取个人动态
let userPosts = ref([])
const userPost = () => {
  getUserPost().then((res:any) => {
    if (res.code === 200) {
      userPosts.value = res.data
    }
  })
}

//修改用户昵称
let userFrom = ref({});

const updateNickName = () => {
  ElMessageBox.prompt('请输入您的新昵称', '修改昵称', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/, // 允许中文、英文字母和数字
    inputErrorMessage: '昵称只能包含中文、英文字母和数字',
  }).then(({ value }) => {
    userFrom.value = {
      nickName: value
    };
    exitNickName(userFrom.value).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success("修改成功");
      } else {
        ElMessage.error("修改失败" + res.msg);
      }}).catch(() => {
      ElMessage.error("请求失败");
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '昵称修改已取消',
    });
  });
};

let  signatures = ref('')
//修改个性签名
const updateSignatures = () => {
  ElMessageBox.prompt('请输入您的个性签名', '个性签名', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^.{1,100}$/, // 假设个性签名的长度限制为1到50个字符
    inputErrorMessage: '签名长度必须在1到50个字符之间',
  }).then(({ value }) => {
    signatures.value = value
    exitSignatures(signatures.value).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success("个性签名修改成功");
      } else {
        ElMessage.error("个性签名修改失败" + res.msg);
      }
    }).catch(() => {
      ElMessage.error("请求失败");
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '个性签名修改已取消',
    });
  });
};

const updatePassword = () => {
  let passwordForm: passwordForm = {
    oldPassword: '',
    newPassword: ''
  }
  // 第一个输入框：输入旧密码
  ElMessageBox.prompt('请输入您的旧密码', '旧密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^.*$/,
    inputErrorMessage: '密码不能为空',
  })
      .then(({ value }) => {
        // 这里可以处理旧密码的逻辑
        console.log('旧密码:', value);
        passwordForm.oldPassword = value
        // 第二个输入框：输入新密码
        ElMessageBox.prompt('请输入您的新密码', '新密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*]).{8,16}$/,
          inputErrorMessage: '密码必须包含数字、字母和特殊字符，长度为8-20位',
        })
            .then(({ value }) => {
              // 这里可以处理新密码的逻辑
              console.log('新密码:', value);
              passwordForm.newPassword = value
              console.log(passwordForm)
              exitPassword(passwordForm).then((res: any) => {
                if (res.code === 200) {
                  ElMessage.success("密码修改成功");
                  router.push('/')
                  store.commit('SET_TOKEN','')
                } else {
                  ElMessage.error("密码修改失败" + res.msg);
                }
              })
            })
            .catch(() => {
              ElMessage({
                type: 'info',
                message: '新密码输入已取消',
              });
            });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '旧密码输入已取消',
        });
      });

};

onMounted(() => {
  nickName.value = store.state.nickName
  avatarImg.value = store.state.avatar
  userPost()
})


</script>
<template>
  <div style="width: 100%;display: flex;flex-direction: column; justify-content: center; align-items: center;padding-top: 60px;" class="mineBg">
    <el-card style="width:800px;;display: flex;flex-direction: column;justify-content: space-between;align-items:center">
      <div style="display: flex; flex-direction: column; justify-content: center; align-items: center" >
        <el-avatar shape="circle" :size="200" fit="fill"  src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
        <p style="font-size: 32px">{{nickName}}</p>
        <p style="width: 220px;font-size: 12px;text-align: center;overflow: hidden;text-overflow:ellipsis;white-space:nowrap;">家人们家人们</p>
      </div>
    </el-card>
    <el-tabs type="border-card" style="width: 800px; margin-top: 20px">
      <el-tab-pane label="个人动态" >
        <div style="display: flex;flex-direction: column;justify-content: center;align-items: center">
          <NewsComment :posts="userPosts"></NewsComment>
        </div>
      </el-tab-pane>
      <el-tab-pane label="个人信息">
        <el-card style="display:flex;flex-direction:column;justify-content:space-between;align-items:center;max-width: 600px;margin: 20px auto 0;" >
          <div style="width:500px;display: flex;justify-content: space-evenly;align-items: center">
            <span style="width: 200px">用户头像</span>
            <div style="width: 200px;padding-left: 28px">
              <el-avatar shape="square" :size="20" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
            </div>
            <el-upload
                ref="upload"
                action="#"
                :on-change="handleExceed"
                :auto-upload=false
                :limit="1"
                :show-file-list="false"
            >
              <el-button type="success" link @click="submitUpload">修改</el-button>
            </el-upload>
          </div>
          <div style="width:500px;display: flex;justify-content: space-evenly;align-items: center;margin-top: 10px">
            <span style="width: 200px">用户昵称</span>
            <span style="width: 200px">我爱吃草莓</span>
            <el-button type="success" link @click="updateNickName">修改</el-button>
          </div>
          <div style="width:500px;display: flex;justify-content: space-evenly;align-items: center; margin-top: 10px">
            <span style="width: 200px">个性签名</span>
            <span style="width: 200px">家人们家人们</span>
            <el-button type="success" link @click="updateSignatures">修改</el-button>
          </div>

          <div style="width:500px;display: flex;justify-content: space-evenly;align-items: center;margin-top: 10px">
            <span style="width: 200px">修改密码</span>
            <div style="width: 200px"></div>
            <el-button type="success" link @click="updatePassword">修改</el-button>
          </div>

          <div style="width:500px;display: flex;justify-content: space-around;align-items: center;margin-top: 10px">
            <span style="width: 200px;">我的喜好</span>
            <div style="width: 200px;">
              <el-tag type="primary">篮球</el-tag>
              <el-tag type="success" style="margin-left: 6px">羽毛球</el-tag>
            </div>
            <div style="width: 30px"></div>
          </div>

        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>


</template>
<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

</style>
